package com.blog.controller;


import com.blog.common.Result.Result;
import com.blog.common.constant.MessageConstant;
import com.blog.dto.UserEmail;
import com.blog.dto.UserRegisterDto;
import com.blog.entity.User;
import com.blog.mapper.UserMapper;
import com.blog.utils.AliOssUtil;
import com.blog.utils.MailUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/common")
@Api(tags = "公共接口")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码接口
     * @param
     * @param
     * @return
     */
    @PostMapping("/sendCode")
    @ApiOperation(value = "发送验证码接口")
    public Result<String> sendCode(@RequestBody UserEmail userEmail){
        String email = userEmail.getEmail();
        log.info("发送验证码：{}",email);
        // 生成验证码
        if (!email.isEmpty()){
            // 生成验证码
            String code = MailUtils.achieveCode();
//            String code = "1234";
            log.info("验证码为：{}",code);
            // 发送邮件
            try {
                // 保存验证码到redis
                redisTemplate.opsForValue().set(email,code,3, TimeUnit.MINUTES);

                // 发送邮件
                MailUtils.sendTestMail(email,code);
                return Result.success("发送成功");
            } catch (MessagingException e) {
                throw new RuntimeException("发送失败");
            }
        }
        return Result.error("发送失败");
    }

    /**
     * 上传照片接口
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传照片接口")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file.getOriginalFilename());
        try {
            String path = aliOssUtil.upload(file);
            return Result.success(path);
        } catch (IOException e) {
            log.info("文件上传失败，{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}
